import {
  DownOutlined,
  RedoOutlined,
  RestOutlined,
} from '@ant-design/icons';
import { Button, message, Drawer, Space, Modal, Dropdown, Menu, Tag, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { ProDescriptions } from '@ant-design/pro-components';
import { useAccess, Access } from 'umi';
import { useRequestHandle, getSorter } from '@/utils/utils';
import { query, get, getUseRecycleBinAttributeInfos, restore } from './service';
import operation from './operation';
import BatchRemove from './components/BatchRemove';
import BatchRestore from './components/BatchRestore';
import ProMaxTable from '@/components/ProMaxTable';

const Recycle = () => {
  const [binAttr, setBinAttr] = useState([]);
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const { canOperation, canShowOption, canShowMoreOption } = useAccess();

  // 是否显示操作列
  const isShowOptionColumn = canShowOption([
    operation.resotre,
    operation.delete,
    operation.detailQuery,
  ]);
  // 是否显示更多操作列
  const isShowMoreOptionColumn = canShowMoreOption([operation.delete, operation.restore]);

  // 刷新
  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 数据恢复
  const restoreRequest = useRequestHandle(restore, () => {
    message.success('操作成功.');
    reload();
  });



  // 操作-更多处理
  const moreOptionHandle = (key, record) => {
    switch (key) {
  
      case 'restore':
        Modal.confirm({
          title: '系统提示',
          icon: <RedoOutlined />,
          content: '确定要恢复该数据吗？',
          okText: '确定',
          okType: 'primary',
          cancelText: '取消',
          onOk() {
            restoreRequest.run({ id: record.id });
          },
        });
        break;
      default:
        break;
    }
  };

  // 获取模块信息列表
  useEffect(() => {
    async function fetchData() {
      const res = await getUseRecycleBinAttributeInfos();
      setBinAttr(res && res.success ? res.data : []);
    }
    fetchData();
  }, []);

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      fixed: 'left',
      width: 50,
    },
    {
      title: '模块名称',
      dataIndex: 'entityClassFullName',
      fixed: 'left',
      hideInSearch: false,
      copyable: true,
      ellipsis: true,
      width: 360,
      render: (dom, entity) => (
        <a
          onClick={async () => {
            const res = await get({ id: entity.id });
            setRow({ ...entity, ...res.data });
          }}
        >
          {dom}
        </a>
      ),
      renderFormItem: () => {
        return (
          <TreeSelect
            style={{ width: '100%' }}
            treeData={binAttr}
            placeholder="默认查询全部"
            treeDefaultExpandAll
          />
        );
      },
    },
    {
      title: '恢复状态',
      dataIndex: 'isRestored',
      hideInSearch: true,
      width: 100,
      render: (_, record) => {
        const isChecked = record.isRestored;
        return isChecked ? <Tag color="#87d068">已恢复</Tag> : <Tag color="#f50">可恢复</Tag>;
      },
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      width: 170,
      hideInSearch: true,
      copyable: true,
      ellipsis: true,
    },
    {
      title: '用户代理',
      dataIndex: 'userAgent',
      hideInSearch: true,
      hideInTable: true,
      hideInDescriptions: false,
      width: 180,
    },
    {
      title: '内容',
      dataIndex: 'body',
      hideInSearch: true,
      hideInTable: true,
      valueType: 'jsonCode',
      width: 130,
    },
    {
      title: '删除人',
      dataIndex: 'operationUserName',
      hideInSearch: true,
      copyable: true,
      ellipsis: true,
      width: 180,
    },
    {
      title: '删除时间',
      dataIndex: 'created',
      valueType: 'dateTime',
      width: 170,
      sorter: true,
      hideInSearch: true,
      hideInForm: true,
      hideInDescriptions: false,
    },
    {
      title: '恢复人',
      dataIndex: 'restoreUserName',
      hideInSearch: true,
      hideInTable: true,
      copyable: true,
      hideInDescriptions: false,
      width: 180,
    },
    {
      title: '恢复时间',
      dataIndex: 'updated',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInTable: true,
      hideInForm: false,
      sorter: true,
      hideInDescriptions: false,
    },
    {
      title: '时间范围',
      dataIndex: 'rangeTime',
      valueType: 'dateRange',
      width: 250,
      hideInSearch: false,
      hideInForm: true,
      hideInTable: true,
      hideInDescriptions: true,
    },
    {
      title: '状态',
      dataIndex: 'isRestoredSelect',
      valueType: 'select',
      valueEnum: {
        0: { text: '可恢复', status: 'Default' },
        1: { text: '已恢复', status: 'Default' },
      },
      width: 100,
      hideInSearch: false,
      hideInForm: true,
      hideInTable: true,
      hideInDescriptions: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 135,
      hideInTable: !isShowOptionColumn,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Access accessible={canOperation(operation.detailQuery)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                const res = await get({ id: record.id });
                setRow({ ...record, ...res.data });
              }}
            >
              查看
            </Button>
          </Access>
          <Access accessible={isShowMoreOptionColumn}>
            <Dropdown
              overlay={
                <Menu
                  onClick={(e) => {
                    moreOptionHandle(e.key, record);
                  }}
                >
                  {canOperation(operation.restore) ? (
                    <Menu.Item key="restore">
                      <RestOutlined /> 恢复
                    </Menu.Item>
                  ) : null}
                 
                </Menu>
              }
            >
              <Button size="small">
                更多 <DownOutlined />
              </Button>
            </Dropdown>
          </Access>
        </Space>
      ),
    },
  ];

  return (
    <>
      <ProMaxTable
        headerTitle="数据列表"
        actionRef={actionRef}
        rowKey="id"
        search={true}
        options={{
          search: canOperation(operation.query)
            ? {
                placeholder: '请输入关键字',
              }
            : false,
          fullScreen: true,
        }}
        toolBarRender={() => [
          <Access
            key="batcn-restore"
            accessible={canOperation(operation.batchRestore) && selectedRowKeys.length > 0}
          >
            <BatchRestore
              ids={selectedRowKeys}
              onSuccess={() => {
                setSelectedRowKeys([]);
                reload();
              }}
            />
          </Access>,
          <Access
            key="batcn-remove"
            accessible={canOperation(operation.batchDelete) && selectedRowKeys.length > 0}
          >
            <BatchRemove
              ids={selectedRowKeys}
              onSuccess={() => {
                setSelectedRowKeys([]);
                reload();
              }}
            />
          </Access>,
        ]}
        request={async (params, sorter, filter) => {
          const data = params;
          data.pageIndex = params.current;
          if (data.hasOwnProperty('rangeTime') && data.rangeTime.length === 2) {
            // eslint-disable-next-line prefer-destructuring
            data.startTime = params.rangeTime[0];
            // eslint-disable-next-line prefer-destructuring
            data.endTime = params.rangeTime[1];
          }
          if (data.isRestoredSelect) {
            data.isRestored = data.isRestoredSelect === '1';
          }
          const result = await query({ ...data, ...getSorter(sorter), filter });
          if (result.success) {
            return {
              ...result,
              data: result.data.items,
              total: result.data.totalItems,
            };
          }
          return [];
        }}
        scroll={{
          x: 1300,
        }}
        postData={(data) => {
          return !data ? [] : data;
        }}
        pagination={true}
        columns={columns}
        rowSelection={
          canOperation(operation.batchRestore) || canOperation(operation.batchDelete)
            ? {
                alwaysShowAlert: true,
                onChange: (rowKeys) => {
                  setSelectedRowKeys(rowKeys);
                },
              }
            : false
        }
      />

      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <ProDescriptions
            column={1}
            title={row?.accountName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </>
  );
};

export default Recycle;
